# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_socket_server.py 
@time: 2019/7/11 上午11:35
"""
'''
创建socket服务器
'''

from socket import socket, AF_INET, SOCK_STREAM
import time

def echo_handler(address, client_sock):
    print('Got connection from {},连接时间为{}'.format(address,time.ctime()))
    while True:
        msg = client_sock.recv(8192)
        if not msg:
            break
        msg = msg + ' 服务器返回时间:'.encode('utf-8') + time.ctime().encode('utf-8')
        client_sock.sendall(msg)

    client_sock.close()

def echo_server(address, backlog=5):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(address)
    sock.listen(backlog)
    while True:
        client_sock, client_addr = sock.accept()
        echo_handler(client_addr,client_sock)


if __name__ == '__main__':
    echo_server(('', 20000))